package com.netflexitysolutions.amazonws.ec2.internal.operations;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.amazonaws.ec2.doc._2009_04_04.DescribeKeyPairsInfoType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeKeyPairsItemType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeKeyPairsResponseItemType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeKeyPairsResponseType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeKeyPairsType;
import com.netflexitysolutions.amazonws.ec2.EC2;
import com.netflexitysolutions.amazonws.ec2.KeyPair;

public class DescribeKeyPairsOperation extends ObjectSetOperationExecutor<DescribeKeyPairsType, List<KeyPair>> {

	public DescribeKeyPairsOperation(EC2 ec2, Set<String> objectIds) {
		super(ec2, objectIds);
	}

	@Override
	protected List<KeyPair> call(DescribeKeyPairsType request) {
		request.setKeySet(createKeyNameElement());
		
		DescribeKeyPairsResponseType response = getEC2().getService().describeKeyPairs(request);
		
		List<KeyPair> result =  new ArrayList<KeyPair>();
		if (response.getKeySet() != null) {
			List<DescribeKeyPairsResponseItemType> list = response.getKeySet().getItem();
			for (DescribeKeyPairsResponseItemType item : list) {
				result.add(toDomainModel(item));
			}
		}
		
		return result;
	}

	private KeyPair toDomainModel(DescribeKeyPairsResponseItemType item) {
		KeyPair keyPair = new KeyPair();	
		keyPair.setKeyName(item.getKeyName());
		keyPair.setKeyFingerprint(item.getKeyFingerprint());
		return keyPair;
	}

	private DescribeKeyPairsInfoType createKeyNameElement() {
		
		if(objectIds == null) {
			return null;
		}
		
		DescribeKeyPairsInfoType element = new DescribeKeyPairsInfoType();
		List<DescribeKeyPairsItemType> list = element.getItem();
		for (String keyNames : objectIds) {
			DescribeKeyPairsItemType item = new DescribeKeyPairsItemType();
			item.setKeyName(keyNames);
			list.add(item);
		}
		return element;
	}

	
}
